import { _decorator, Component, Vec2, Vec3 } from 'cc';
import { JoystickController } from '../core/JoystickController';
const { ccclass, property } = _decorator;

/**
 * 角色控制器
 * 
 * 功能：
 * 1. 处理角色的移动和转向
 * 2. 管理角色的物理碰撞
 * 3. 处理角色的动画状态
 * 4. 控制角色的技能释放
 * 
 * 特点：
 * 1. 平滑的移动控制
 * 2. 基于状态的动画系统
 * 3. 可配置的物理参数
 * 4. 支持多种移动模式
 */
@ccclass('CharacterController')
export class CharacterController extends Component {
    @property
    public moveSpeed: number = 5;

    @property
    public rotateSpeed: number = 180;

    private moveDirection: Vec3 = new Vec3();
    private targetRotation: number = 0;

    update(deltaTime: number) {
        this.handleMovement(deltaTime);
        this.handleRotation(deltaTime);
    }

    private handleMovement(deltaTime: number) {
        const input = JoystickController.instance.getMoveDirection();
        
        // 转换2D输入为3D移动
        this.moveDirection.set(
            input.x * this.moveSpeed,
            input.y * this.moveSpeed,
            0
        );

        const currentPos = this.node.position;
        currentPos.add(this.moveDirection.multiplyScalar(deltaTime));
        this.node.setPosition(currentPos);
    }

    private handleRotation(deltaTime: number) {
        if (!JoystickController.instance.getIsMoving()) {
            return;
        }

        const input = JoystickController.instance.getMoveDirection();
        this.targetRotation = Math.atan2(input.y, input.x) * 180 / Math.PI;

        // 平滑旋转
        let currentRotation = this.node.eulerAngles.z;
        const rotationDiff = this.targetRotation - currentRotation;
        
        if (Math.abs(rotationDiff) > 1) {
            const rotationStep = this.rotateSpeed * deltaTime;
            currentRotation += Math.sign(rotationDiff) * rotationStep;
            this.node.setRotationFromEuler(0, 0, currentRotation);
        }
    }

    public setMoveSpeed(speed: number) {
        this.moveSpeed = speed;
    }
} 